﻿using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;

namespace PuzzleWCF
{
    public class PuzzleRakingService : IPuzzleRakingService
    {
        public int SavePlayerTime(Player player)
        {
            int retorno;
            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PuzzleDatabase"].ConnectionString))
            {
                const string sql = "INSERT INTO Players (Name,Time) VALUES (@NAME,@TIME)";
                var cmd = new SqlCommand(sql, conn);
                cmd.Parameters.Add(new SqlParameter("@NAME", player.Name));
                cmd.Parameters.Add(new SqlParameter("@TIME", player.Time));

                try
                {
                    conn.Open();
                    retorno = cmd.ExecuteNonQuery();
                }
                finally
                {
                    conn.Close();
                }

            }
            return retorno;
        }

        public IEnumerable<Player> GetTop5()
        {
            var players = new List<Player>();
            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PuzzleDatabase"].ConnectionString))
            {
                const string sql = "Select TOP 5 Name,Time From Players p Order By p.Time";
                var cmd = new SqlCommand(sql, conn);

                try
                {
                    conn.Open();
                    var dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        var player = new Player
                        {
                            Name = dr.GetString(0),
                            Time = dr.GetTimeSpan(1)
                        };
                        players.Add(player);
                    }
                }
                finally
                {
                    conn.Close();
                }

            }
            return players;
        }

        //public IEnumerable<Player> GetAllPlayerTimes(int page)
        //{
        //    return null;
        //}
    }
}
